﻿using System;
using System.Web.UI.WebControls;

namespace VioletDevelopmentLaboratory.Net.Web
{
	[Serializable]
	internal class MessagePageParameter
	{
		public MessagePageParameter()
		{
			AutoRedirectToReturnUrl = false;
			RedirectTimeout = -1;
		}

		private String message;
		public String Message { get { return message; } set { message = value; } }

		private String redirectUrl;
		public String RedirectUrl { get { return redirectUrl; } set { redirectUrl = value; } }

		private Boolean autoRedirectToReturnUrl;
		public Boolean AutoRedirectToReturnUrl { get { return autoRedirectToReturnUrl; } set { autoRedirectToReturnUrl = value; } }

		private Int32 redirectTimeout;
		public Int32 RedirectTimeout { get { return redirectTimeout; } set { redirectTimeout = value; } }
	}

	public abstract class MessagePage : PageBase
	{
		protected Literal MainMessageLiteral;
		protected Literal SubMessageLiteral;

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			MessagePageParameter messagePageParameter = null;

			if (Session["!VWeb_MessagePageParameter"] != null)
			{
				messagePageParameter = (MessagePageParameter)Session["!VWeb_MessagePageParameter"];

				Session.Remove("!VWeb_MessagePageParameter");
			}
			else
			{
				messagePageParameter = new MessagePageParameter();
				messagePageParameter.Message = VUtility.GetVWebGlobalResource("General_RedirectHomepage");
				messagePageParameter.RedirectUrl = ResolveUrl("~/");
				messagePageParameter.AutoRedirectToReturnUrl = true;
				messagePageParameter.RedirectTimeout = 3;
			}

			this.MainMessageLiteral.Text = messagePageParameter.Message;

			if (messagePageParameter.AutoRedirectToReturnUrl && messagePageParameter.RedirectTimeout > -1)
			{
				SubMessageLiteral.Text += String.Format(VUtility.GetVWebGlobalResource("General_RedirectTimeout"), messagePageParameter.RedirectTimeout, ResolveClientUrl(messagePageParameter.RedirectUrl));

				this.ClientScript.RegisterStartupScript(this.GetType(), "RedirectScript", String.Format("setTimeout(\"self.location.href = '{0}'\", {1});", ResolveClientUrl(messagePageParameter.RedirectUrl), messagePageParameter.RedirectTimeout * 1000), true);
			}
		}
	}
}